import React, { useEffect, useState } from "react";
import { Modal ,message} from "antd";

const newData = {
    title: "",
    body: "",
}
const MyModal = (props:any) => {
    const { visible = false, setVisible, editData } = props
      const [confirmVisible, setConfirmVisible] = useState(false);
    const [data, setData] = useState(newData);

   const onConfirmOk=()=>{
    props.onOk(data,editData?'edit':'add')
    closeConfirmModal()
    closeModal();
   }
   const closeConfirmModal =()=>{
      setConfirmVisible(false)
   }
    const onOk = () => {
        if(!data.title||!data.body){
            message.warning('输入不完整');
            return;
          }
          setConfirmVisible(true)
       
    };
    useEffect(() => {
        if (visible) {
            console.log("editData:",editData)
            editData?setData(editData):setData(newData)
        }
    }, [visible, editData])
    const closeModal = () => {
        setVisible(false);
    };
    const changeData = (e:any, type?:string) => {
        if (!type) return;
        const _data = { ...data };
        _data[type] = e.target.value;
        setData(_data)
    }
    return (
        <>
            <Modal
                title={editData ? '编辑' : '新增'}
                open={visible}
                onOk={onOk}
                onCancel={closeModal}
                afterClose={closeModal}
            >
                <input className="notes__title" type="text" placeholder="标题" value={data.title} onChange={e => changeData(e, 'title')} />
                <textarea className="notes__body" placeholder="内容" onChange={e => changeData(e, 'body')} value={data.body} />
            </Modal>
            <Modal open={confirmVisible}  onOk={onConfirmOk}
                onCancel={closeConfirmModal}
                afterClose={closeConfirmModal}>确认保存？</Modal>
        </>
    );
};

export default MyModal;